package com.hmall.common.interceptors;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //1.获取请求头中的用户id
        String userID = request.getHeader("user-info");
        //2.判断用户id是否为空
        //3.将用户id存入ThreadLocal中
        if(StrUtil.isNotBlank(userID)){
            UserContext.setUser(Long.parseLong(userID));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            // 清理用户
          UserContext.removeUser();
    }
}
